package me.shiqiang.im.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
import static com.fasterxml.jackson.databind.DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY;

/**
 * @author cuishiqiang
 * @date 2017/12/7 下午5:40
 */
public class JsonUtils {
    private static JsonUtils ourInstance = new JsonUtils();

    public static JsonUtils getInstance() {
        return ourInstance;
    }

    private ObjectMapper mapper;

    private JsonUtils() {
        mapper = new ObjectMapper();
        mapper.configure(USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
        mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    }

    public ObjectMapper getMapper() {
        return mapper;
    }

    public String toJson(Object object) throws JsonProcessingException {
        return mapper.writeValueAsString(object);
    }

    public <T> T fromJson(String str, Class<T> tClass) throws IOException {
        return mapper.readValue(str, tClass);
    }
}
